/**
 * 抖音小游戏入口文件
 */

// 添加Canvas圆角矩形兼容性函数
function drawRoundRect(ctx, x, y, width, height, radius) {
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
}

// 引入登录界面模块
const LoginView = require('./views/login.js');
const MainView = require('./views/mainView.js');
const GameView = require('./views/gameView.js');
const SettingsView = require('./views/settingsView.js');
const RankingView = require('./views/rankingView.js');

// 游戏实例
const game = {
  // 游戏状态
  state: {
    score: 0,
    level: 1,
    isRunning: false,
    resourcesLoaded: false,
    currentScene: 'login', // 当前场景：login, main, game, settings
    difficulty: 'medium', // 游戏难度: slow, medium, fast
    highScore: 0, // 历史最高分
    gameOver: false, // 游戏结束状态，用于显示返回按钮
    showScorePopup: false, // 是否显示分数提示弹窗
    // 侧边栏任务相关状态
    sidebarTask: {
      showGuidePopup: false, // 是否显示侧边栏引导弹窗
      hasCompletedToday: false, // 今日是否已完成侧边栏任务
      lastCompleteDate: null, // 上次完成日期
      continuousDays: 0 // 连续完成天数
    },
    // 设置项
    settings: {
      soundEnabled: true,     // 音效开关
      vibrationEnabled: true, // 震动开关
      musicEnabled: true,     // 音乐开关
      autoStart: false        // 自动开始
    },
    // 触摸状态
    touch: {
      active: false,
      x: 0,
      y: 0
    },
    // 广告相关状态
    ad: {
      bannerAd: null, // Banner广告实例
      bannerAdLoaded: false, // Banner广告是否已加载
      showBannerAd: true, // 是否显示Banner广告
      lastScene: null // 上一个场景，用于检测场景切换
    }
   },
  
  // 游戏元素
    gameElements: {
      // 基础配置会在setupCanvas后根据屏幕尺寸调整
      player: {
        x: 0,
        y: 0,
        baseRadius: 15,
        radius: 15,
        color: '#3498DB',
        baseSpeed: 2,
        speed: 2
      },
    enemyStartMaxSpeed:0.7,//初始最大速度
    enemyStartSpawnRate: 5000, // 初始敌人生成秒数 
    enemies: [],
    enemySpawnTimer: 0,
    enemySpawnRate: 5000, // 毫秒    
    enemyMinSpeed: 0.3,
    enemyMaxSpeed: 0.5,
    enemyMinRadius: 10,
    enemyMaxRadius: 20,
    // 存储原始值用于比例缩放
    baseEnemyMinRadius: 10,
    baseEnemyMaxRadius: 20,
    baseEnemyMinSpeed: 0.3,
    baseEnemyMaxSpeed: 0.5
    },
  
  // 游戏资源
  resources: {
    logo: null
  },
  
  // 初始化游戏
  init: function() {
    console.log('游戏初始化');
    // 初始化物理引擎、场景等
    this.setupCanvas();
    this.bindEvents();
    this.loadResources();
    this.loadSettings();
    
    // 初始化Banner广告
    this.initBannerAd();
  },
  
  // 初始化Banner广告
  initBannerAd: function() {
    try {
      // 检查是否在抖音环境中
      if (typeof tt !== 'undefined' && tt.createBannerAd) {
        console.log('初始化Banner广告');
        // 创建Banner广告实例
        this.state.ad.bannerAd = tt.createBannerAd({
          adUnitId: 'adunit-xxxx', // 替换为实际的广告位ID
          style: {
            top: this.height - 100, // 底部位置
            left: 0,
            width: this.width
          }
        });
        
        // 监听广告加载成功事件
        this.state.ad.bannerAd.onLoad(() => {
          console.log('Banner广告加载成功');
          this.state.ad.bannerAdLoaded = true;
          // 只在主页面显示广告
          if (this.state.currentScene === 'main') {
            this.showBannerAd();
          }
        });
        
        // 监听广告加载失败事件
        this.state.ad.bannerAd.onError((err) => {
          console.error('Banner广告加载失败:', err);
          this.state.ad.bannerAdLoaded = false;
        });
        
        // 监听广告尺寸变化事件
        this.state.ad.bannerAd.onResize((res) => {
          console.log('Banner广告尺寸变化:', res);
          // 根据广告尺寸调整广告位置
          if (this.state.ad.bannerAd) {
            this.state.ad.bannerAd.style.top = this.height - res.height;
          }
        });
      } else {
        console.log('当前环境不支持抖音Banner广告');
      }
    } catch (error) {
      console.error('初始化Banner广告失败:', error);
    }
  },
  
  // 显示Banner广告
  showBannerAd: function() {
    try {
      if (this.state.ad.bannerAd && this.state.ad.bannerAdLoaded && this.state.ad.showBannerAd) {
        console.log('显示Banner广告');
        this.state.ad.bannerAd.show();
      }
    } catch (error) {
      console.error('显示Banner广告失败:', error);
    }
  },
  
  // 隐藏Banner广告
  hideBannerAd: function() {
    try {
      if (this.state.ad.bannerAd) {
        console.log('隐藏Banner广告');
        this.state.ad.bannerAd.hide();
      }
    } catch (error) {
      console.error('隐藏Banner广告失败:', error);
    }
  },
  
  // 设置画布
  setupCanvas: function() {
    // 获取系统信息
    const sysInfo = tt.getSystemInfoSync();
    this.canvas = tt.createCanvas();
    this.ctx = this.canvas.getContext('2d');
    this.width = sysInfo.windowWidth;
    this.height = sysInfo.windowHeight;
    
    // 计算比例因子 - 增加20%显示大小
    this.scaleFactor = (Math.min(this.width, this.height) / 400) * 1.2; // 基准尺寸为400
    
    // 根据屏幕比例调整游戏元素大小和速度
    this.gameElements.player.radius = this.gameElements.player.baseRadius * this.scaleFactor;
    this.gameElements.player.speed = this.gameElements.player.baseSpeed * this.scaleFactor;
    this.gameElements.enemyMinRadius = this.gameElements.baseEnemyMinRadius * this.scaleFactor;
    this.gameElements.enemyMaxRadius = this.gameElements.baseEnemyMaxRadius * this.scaleFactor;
    this.gameElements.enemyMinSpeed = this.gameElements.baseEnemyMinSpeed * this.scaleFactor;
    this.gameElements.enemyMaxSpeed = this.gameElements.baseEnemyMaxSpeed * this.scaleFactor;
    this.gameElements.enemyStartMaxSpeed = 0.7 * this.scaleFactor;
    
    console.log('画布设置完成，尺寸:', this.width, 'x', this.height);
    console.log('比例因子:', this.scaleFactor);
  },
  
  // 绑定事件
  bindEvents: function() {
    // 触摸事件监听
    tt.onTouchStart(this.onTouchStart.bind(this));
    tt.onTouchMove(this.onTouchMove.bind(this));
    tt.onTouchEnd(this.onTouchEnd.bind(this));
  },
  
  // 加载资源
  loadResources: function() {
    console.log('资源加载中...');
    
    // 创建logo图片对象
    this.resources.logo = tt.createImage();
    this.resources.logo.src = 'asset/img/game_logo.png';
    
    // 监听图片加载完成事件
    this.resources.logo.onload = () => {
      console.log('Logo图片加载完成');
      this.state.resourcesLoaded = true;
      // 资源加载完成后开始游戏
      this.start();
    };
    
    // 监听图片加载失败事件
    this.resources.logo.onerror = () => {
      console.error('Logo图片加载失败');
      // 即使图片加载失败也要设置资源加载完成状态，确保能显示登录界面
      this.state.resourcesLoaded = true;
      // 继续游戏
      this.start();
    };
  },
  
  // 开始游戏
  start: function() {
    console.log('游戏开始');
    this.state.isRunning = true;
    // 开始游戏主循环
    this.gameLoop();
  },
  
  // 游戏主循环
  gameLoop: function() {
    if (this.state.isRunning && this.state.currentScene === 'game') {
      this.update();
    }
    this.render();
    requestAnimationFrame(this.gameLoop.bind(this));
  },
  
  // 更新游戏逻辑
  update: function() {
    // 根据难度调整游戏速度
    let gameSpeed = 1;
    switch(this.state.difficulty) {
      case 'slow':
        gameSpeed = 0.8;
        break;
      case 'medium':
        gameSpeed = 1;
        break;
      case 'fast':
        gameSpeed = 1.5;
        break;
    }
    
    // 更新玩家位置（跟随触摸）
    if (this.state.touch.active) {
      const player = this.gameElements.player;
      const dx = this.state.touch.x - player.x;
      const dy = this.state.touch.y - player.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance > 5) { // 防止抖动
        player.x += (dx / distance) * player.speed * gameSpeed;
        player.y += (dy / distance) * player.speed * gameSpeed;
        
        // 边界检查
        player.x = Math.max(player.radius, Math.min(this.width - player.radius, player.x));
        player.y = Math.max(player.radius, Math.min(this.height - player.radius, player.y));
      }
    }
    // 游戏逻辑更新完成
    
    // 更新敌人位置
    for (let i = this.gameElements.enemies.length - 1; i >= 0; i--) {
      const enemy = this.gameElements.enemies[i];
      enemy.x += enemy.vx * gameSpeed;
      enemy.y += enemy.vy * gameSpeed;
      
      // 移除超出屏幕的敌人
      if (enemy.x < -enemy.radius || enemy.x > this.width + enemy.radius ||
          enemy.y < -enemy.radius || enemy.y > this.height + enemy.radius) {
        this.gameElements.enemies.splice(i, 1);
      }
    }
    
    // 生成新敌人
    this.gameElements.enemySpawnTimer += 16; // 假设60fps
    if (this.gameElements.enemySpawnTimer >= this.gameElements.enemySpawnRate) {
      this.spawnEnemy();
      this.gameElements.enemySpawnTimer = 0;
    }
    
    // 检测碰撞
    this.checkCollisions();
    
    // 更新分数和等级
    this.state.score += 1;
    if (this.state.score % 500 === 0) {
      this.state.level += 1;
      // 随着等级提高增加难度
      this.gameElements.enemySpawnRate = Math.max(300,  this.gameElements.enemyStartSpawnRate - (this.state.level - 1) * 50);
      this.gameElements.enemyMaxSpeed = Math.min(8, this.gameElements.enemyStartMaxSpeed + (this.state.level - 1) * 0.2);
    }
  },
  
  // 生成敌人
  spawnEnemy: function() {
    const minRadius = this.gameElements.enemyMinRadius;
    const maxRadius = this.gameElements.enemyMaxRadius;
    const radius = minRadius + Math.random() * (maxRadius - minRadius);
    
    // 随机位置（从屏幕边缘）
    let x, y;
    const side = Math.floor(Math.random() * 4); // 0: 上, 1: 右, 2: 下, 3: 左
    
    switch(side) {
      case 0: // 上
        x = Math.random() * this.width;
        y = -radius;
        break;
      case 1: // 右
        x = this.width + radius;
        y = Math.random() * this.height;
        break;
      case 2: // 下
        x = Math.random() * this.width;
        y = this.height + radius;
        break;
      case 3: // 左
        x = -radius;
        y = Math.random() * this.height;
        break;
    }
    
    // 计算朝向玩家的速度
    const playerX = this.gameElements.player.x;
    const playerY = this.gameElements.player.y;
    const dx = playerX - x;
    const dy = playerY - y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    
    const speed = this.gameElements.enemyMinSpeed + 
                 Math.random() * (this.gameElements.enemyMaxSpeed - this.gameElements.enemyMinSpeed);
   
    // 创建敌人对象
    const enemy = {
      x: x,
      y: y,
      radius: radius,
      color: this.getRandomEnemyColor(),
      vx: (dx / distance) * speed,
      vy: (dy / distance) * speed
    };
     console.log(`生成敌人：半径${radius.toFixed(2)}，速度${speed.toFixed(2)}，位置(${enemy.vx.toFixed(2)}, ${enemy.vy.toFixed(2)})`);
    this.gameElements.enemies.push(enemy);
  },
  
  // 获取随机敌人颜色
  getRandomEnemyColor: function() {
    const colors = ['#E74C3C', '#E67E22', '#9B59B6', '#F39C12', '#8E44AD'];
    return colors[Math.floor(Math.random() * colors.length)];
  },
  
  // 检测碰撞
  checkCollisions: function() {
    const player = this.gameElements.player;
    
    for (let enemy of this.gameElements.enemies) {
      const dx = player.x - enemy.x;
      const dy = player.y - enemy.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < player.radius + enemy.radius) {
        // 发生碰撞，游戏结束
        this.gameOver();
        break;
      }
    }
  },
  
  
  
  // 渲染画面
  render: function() {
    // 如果资源未加载完成，显示加载信息
    if (!this.state.resourcesLoaded) {
      this.ctx.fillStyle = '#f5f5f5';
      this.ctx.fillRect(0, 0, this.width, this.height);
      this.ctx.fillStyle = '#333';
      this.ctx.font = '20px Arial';
      this.ctx.textAlign = 'center';
      this.ctx.fillText('加载中...', this.width / 2, this.height / 2);
      return;
    }
    
    // 检查场景是否切换，如果切换则控制广告显示状态
    if (this.state.ad.lastScene !== this.state.currentScene) {
      this.handleSceneChange();
    }
    
    // 根据当前场景渲染不同内容
    if (this.state.currentScene === 'login') {
      LoginView.render(this.ctx, this.width, this.height);
    } else if (this.state.currentScene === 'main') {
      MainView.render(this.ctx, this.width, this.height, this.state.highScore);
      //渲染侧边栏引导弹窗（如果需要显示）
      if (this.state.sidebarTask.showGuidePopup) {
        this.renderSidebarGuidePopup(this.ctx, this.width, this.height);
      }
    } else if (this.state.currentScene === 'game') {
      GameView.render(this.ctx, this.width, this.height, this.state, this.gameElements);
    } else if (this.state.currentScene === 'settings') {
      SettingsView.render(this.ctx, this.width, this.height, this.state.settings);
    } else if (this.state.currentScene === 'ranking') {
      RankingView.render(this.ctx, this.width, this.height, this.state.highScore);
    }
  },
  
  // 处理场景切换
  handleSceneChange: function() {
    console.log('场景切换:', this.state.ad.lastScene, '->', this.state.currentScene);
    
    // 控制广告显示/隐藏
    if (this.state.currentScene === 'main') {
      // 主页面显示广告
      this.showBannerAd();
    } else {
      // 其他场景隐藏广告
      this.hideBannerAd();
    }
    
    // 更新上一个场景
    this.state.ad.lastScene = this.state.currentScene;
  },
  
  // 触摸开始事件处理
  onTouchStart: function(e) {
    console.log('触摸开始:', e.touches[0]);
    if (this.state.currentScene === 'game' && this.state.isRunning) {
      const touchX = e.touches[0].clientX;
      const touchY = e.touches[0].clientY;
      this.state.touch.active = true;
      this.state.touch.x = touchX;
      this.state.touch.y = touchY;
    }
  },
  
  // 触摸移动事件处理
  onTouchMove: function(e) {
    if (this.state.currentScene === 'game' && this.state.isRunning) {
      const touchX = e.touches[0].clientX;
      const touchY = e.touches[0].clientY;
      this.state.touch.x = touchX;
      this.state.touch.y = touchY;
    }
  },
  
  // 触摸结束事件处理
  onTouchEnd: function(e) {
    console.log('触摸结束');
    const touchX = e.changedTouches[0].clientX;
    const touchY = e.changedTouches[0].clientY;
    
    // 登录界面的点击处理
    if (this.state.currentScene === 'login') {
      // 检查是否点击了登录按钮
      const isLoginClick = LoginView.checkButtonClick(touchX, touchY, this.width, this.height);
      // 已包含隐式null检查，因为只有当点击按钮时才返回true
      if (isLoginClick) {
        LoginView.handleLogin(this);
      }
    } 
    // 主界面的点击处理
    else if (this.state.currentScene === 'main') {
      // 如果显示侧边栏引导弹窗，先处理弹窗内的点击
      if (this.state.sidebarTask.showGuidePopup) {
        if (this.checkSidebarGuidePopupClick(touchX, touchY)) {
          return;
        }
      }
      
      const button = MainView.checkButtonClick(touchX, touchY, this.width, this.height);
      switch(button) {
        case 'start':
          this.handleStartGame();
          break;
        case 'settings':
          this.handleSettings();
          break;
        case 'ranking':
          this.handleRanking();
          break;
        case 'exit':
          this.handleExit();
          break;
        case 'sidebarGift':
          this.handleSidebarGiftClick();
          break;
      }
    }
    // 设置界面的点击处理
    else if (this.state.currentScene === 'settings') {
      const result = SettingsView.checkButtonClick(touchX, touchY, this.width, this.height);
      // 添加null检查，避免TypeError
      if (result) {
        if (result.type === 'toggle') {
          this.toggleSetting(result.key);
        } else if (result.type === 'back') {
          this.state.currentScene = 'main';
        }
      }
    }
    // 排行榜界面的点击处理
    else if (this.state.currentScene === 'ranking') {
      const action = RankingView.checkButtonClick(touchX, touchY, this.width, this.height);
      // 添加null检查，避免TypeError
      if (action === 'back') {
        this.state.currentScene = 'main';
      }
    }
    // 游戏界面的点击处理
    else if (this.state.currentScene === 'game') {
      // 如果游戏结束但弹窗已关闭，点击任何地方都关闭游戏结束界面
      if (this.state.gameOver && !this.state.showScorePopup) {
        this.handleGameOver();
      } else {
        const action = GameView.checkButtonClick(touchX, touchY, this.width, this.height, this.state);
        switch(action) {
          case 'menu':
          case 'closePopup':
            this.handleGameOver();
            break;
          case 'pause':
            this.pause();
            break;
          case 'resume':
            this.resume();
            break;
          case 'touch':
            if (this.state.isRunning) {
              this.state.touch.active = true;
              this.state.touch.x = touchX;
              this.state.touch.y = touchY;
            }
            break;
        }
      }
    }
  },
  
  // 开始游戏
  handleStartGame: function() {
    console.log('开始游戏');
    
    // 保存当前难度设置
    try {
      tt.setStorageSync('gameDifficulty', this.state.difficulty);
    } catch (e) {
      console.error('保存难度设置失败', e);
    }
    
    // 重置游戏状态
    this.state.score = 0;
    this.state.level = 1;
    this.state.touch.active = false;
    this.state.showScorePopup = false;
    
    // 重置玩家位置和速度
    this.gameElements.player.x = this.width / 2;
    this.gameElements.player.y = this.height / 2;
    // 使用比例因子重置速度
    this.gameElements.player.speed = this.gameElements.player.baseSpeed * this.scaleFactor;
    
    // 清空敌人列表
    this.gameElements.enemies = [];
    this.gameElements.enemySpawnTimer = 0;
    
    // 完全重置所有敌人生成参数，确保游戏每次开始时都是一致的状态
    this.gameElements.enemySpawnRate = 1000; // 重置生成频率
    // 使用比例因子重置敌人参数
    this.gameElements.enemyMinSpeed = this.gameElements.baseEnemyMinSpeed * this.scaleFactor;
    this.gameElements.enemyMaxSpeed = this.gameElements.enemyStartMaxSpeed;
    this.gameElements.enemyMinRadius = this.gameElements.baseEnemyMinRadius * this.scaleFactor;
    this.gameElements.enemyMaxRadius = this.gameElements.baseEnemyMaxRadius * this.scaleFactor;
    
    // 切换到游戏场景并启动游戏
    this.state.currentScene = 'game';
    this.start();
  },
  
  // 选择难度
  handleDifficultySelect: function(level) {
    console.log('选择难度:', level);
    this.state.difficulty = level;
  },
  
  // 打开设置
  handleSettings: function() {
    console.log('打开设置');
    this.state.currentScene = 'settings';
  },
  
  
  
  // 切换设置项
  toggleSetting: function(key) {
    if (this.state.settings.hasOwnProperty(key)) {
      this.state.settings[key] = !this.state.settings[key];
      this.saveSettings();
      
      // 如果是震动设置，测试一下震动
      if (key === 'vibrationEnabled' && this.state.settings[key] && typeof tt.vibrateShort === 'function') {
        tt.vibrateShort({
          type: 'light'
        });
      }
    }
  },
  
  // 保存设置到本地缓存
  saveSettings: function() {
    try {
      tt.setStorageSync('game_settings', this.state.settings);
      console.log('设置已保存');
    } catch (e) {
      console.error('保存设置失败:', e);
    }
  },
  
  // 加载设置
  loadSettings: function() {
    try {
      const res = tt.getStorageSync('game_settings');
      if (res) {
        this.state.settings = { ...this.state.settings, ...res };
        console.log('设置已加载');
      }
    } catch (e) {
      console.error('加载设置失败:', e);
    }
  },
  
  // 打开排行榜
  handleRanking: function() {
    console.log('打开排行榜');
    this.state.currentScene = 'ranking';
  },
  
  // 退出游戏
  handleExit: function() {
    console.log('退出游戏');
    tt.showModal({
      title: '确认退出',
      content: '确定要退出游戏吗？',
      success: function(res) {
        if (res.confirm) {
          tt.exitMiniProgram();
        }
      }
    });
  },
  
  // 处理侧边栏礼包点击
  handleSidebarGiftClick: function() {
    console.log('点击侧边栏礼包');
    // 检查今天是否已经完成任务
    this.checkSidebarTaskStatus();
    
    if (!this.state.sidebarTask.hasCompletedToday) {
      // 显示侧边栏引导弹窗
      this.state.sidebarTask.showGuidePopup = true;
    } else {
      // 提示今日已完成
      tt.showToast({
        title: '今日奖励已领取',
        icon: 'none',
        duration: 2000
      });
    }
  },
  
  // 渲染侧边栏引导弹窗
  renderSidebarGuidePopup: function(ctx, width, height) {
    // 计算比例因子
    const scaleFactor = Math.min(width, height) / 400; // 基准尺寸为400
    
    // 绘制半透明背景遮罩
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(0, 0, width, height);
    
    // 绘制弹窗背景 - 使用比例设置
    const popupWidth = width * 0.8;
    const popupHeight = 300 * scaleFactor;
    const popupX = (width - popupWidth) / 2;
    const popupY = (height - popupHeight) / 2;
    
    ctx.beginPath();
    drawRoundRect(ctx, popupX, popupY, popupWidth, popupHeight, 15 * scaleFactor);
    ctx.fillStyle = 'white';
    ctx.fill();
    
    // 绘制标题 - 使用比例设置字体大小
    ctx.fillStyle = '#E74C3C';
    ctx.font = `bold ${20 * scaleFactor}px Arial`;
    ctx.textAlign = 'center';
    ctx.fillText('抖音首页侧边栏入口奖励', width / 2, popupY + 40 * scaleFactor);
    
    // 绘制步骤说明 - 使用比例设置字体大小和位置
    ctx.fillStyle = '#2C3E50';
    ctx.font = `${16 * scaleFactor}px Arial`;
    ctx.textAlign = 'left';
    
    const stepY = popupY + 80 * scaleFactor;
    const stepSpacing = 40 * scaleFactor;
    const stepX = popupX + 30 * scaleFactor;
    
    ctx.fillText('1. 点击下方「去首页侧边栏」按钮', stepX, stepY);
    ctx.fillText('2. 在侧边栏，点击「极速闪避」', stepX, stepY + stepSpacing);
    ctx.fillText('3. 返回游戏，领取奖励', stepX, stepY + stepSpacing * 2);
    
    // 绘制按钮 - 使用比例设置
    const btnWidth = popupWidth * 0.7;
    const btnHeight = 45 * scaleFactor;
    const btnX = (width - btnWidth) / 2;
    const btnY = popupY + popupHeight - 60 * scaleFactor;
    
    ctx.beginPath();
    drawRoundRect(ctx, btnX, btnY, btnWidth, btnHeight, 25 * scaleFactor);
    ctx.fillStyle = '#27AE60';
    ctx.fill();
    
    ctx.fillStyle = 'white';
    ctx.font = `bold ${18 * scaleFactor}px Arial`;
    ctx.textAlign = 'center';
    ctx.fillText('去首页侧边栏', width / 2, btnY + btnHeight / 2 + 7 * scaleFactor);
    
    // 绘制关闭按钮 - 使用比例设置
    const closeBtnRadius = 15 * scaleFactor;
    const closeBtnX = popupX + popupWidth - closeBtnRadius - 10 * scaleFactor;
    const closeBtnY = popupY + closeBtnRadius + 10 * scaleFactor;
    
    ctx.beginPath();
    ctx.arc(closeBtnX, closeBtnY, closeBtnRadius, 0, 2 * Math.PI);
    ctx.fillStyle = '#E9ECEF';
    ctx.fill();
    
    ctx.strokeStyle = '#ADB5BD';
    ctx.lineWidth = 2 * scaleFactor;
    ctx.beginPath();
    ctx.moveTo(closeBtnX - 8 * scaleFactor, closeBtnY - 8 * scaleFactor);
    ctx.lineTo(closeBtnX + 8 * scaleFactor, closeBtnY + 8 * scaleFactor);
    ctx.moveTo(closeBtnX + 8 * scaleFactor, closeBtnY - 8 * scaleFactor);
    ctx.lineTo(closeBtnX - 8 * scaleFactor, closeBtnY + 8 * scaleFactor);
    ctx.stroke();
  },
  
  // 检查侧边栏引导弹窗点击
  checkSidebarGuidePopupClick: function(touchX, touchY) {
    // 计算比例因子
    const scaleFactor = Math.min(this.width, this.height) / 400; // 基准尺寸为400
    
    const popupWidth = this.width * 0.8;
    const popupHeight = 300 * scaleFactor;
    const popupX = (this.width - popupWidth) / 2;
    const popupY = (this.height - popupHeight) / 2;
    
    // 检查关闭按钮点击 - 使用比例设置
    const closeBtnRadius = 15 * scaleFactor;
    const closeBtnX = popupX + popupWidth - closeBtnRadius - 10 * scaleFactor;
    const closeBtnY = popupY + closeBtnRadius + 10 * scaleFactor;
    const dx = touchX - closeBtnX;
    const dy = touchY - closeBtnY;
    const distance = Math.sqrt(dx * dx + dy * dy);
    
    if (distance <= closeBtnRadius) {
      this.state.sidebarTask.showGuidePopup = false;
      return true;
    }
    
    // 检查去首页侧边栏按钮点击 - 使用比例设置
    const btnWidth = popupWidth * 0.7;
    const btnHeight = 45 * scaleFactor;
    const btnX = (this.width - btnWidth) / 2;
    const btnY = popupY + popupHeight - 60 * scaleFactor;
    
    if (touchX >= btnX && touchX <= btnX + btnWidth && 
        touchY >= btnY && touchY <= btnY + btnHeight) {
      // 使用tt.navigateToScene跳转到侧边栏
      this.navigateToSidebar();
      return true;
    }
    
    return false;
  },
  
  // 跳转到侧边栏
  navigateToSidebar: function() {
    console.log('[侧边栏功能] 引导用户手动进入侧边栏');
    // 关闭弹窗
    this.state.sidebarTask.showGuidePopup = false;
    
    // 不使用tt.navigateToScene API，直接显示引导提示
    tt.showToast({
      title: '请手动从抖音首页侧边栏进入游戏',
      icon: 'none',
      duration: 3000
    });
  },
  
  // 检查侧边栏任务状态
  checkSidebarTaskStatus: function() {
    // 从本地存储获取上次完成日期和连续天数
    const lastCompleteDate = tt.getStorageSync('sidebarTaskLastCompleteDate') || null;
    const continuousDays = tt.getStorageSync('sidebarTaskContinuousDays') || 0;
    const today = new Date().toDateString();
    
    // 更新任务状态
    this.state.sidebarTask.lastCompleteDate = lastCompleteDate;
    this.state.sidebarTask.hasCompletedToday = lastCompleteDate === today;
    this.state.sidebarTask.continuousDays = continuousDays;
  },
  
  // 检查游戏快捷入口状态
  checkShortcutStatus: function() {
    console.log('[快捷入口] 检查游戏快捷入口状态');
    
    // 尝试调用tt.checkShortcut方法检查快捷入口是否已添加
    try {
      tt.checkShortcut({
        success: (res) => {
          console.log('[快捷入口] 检查成功', res);
          // 保存快捷入口状态到本地存储
          tt.setStorageSync('shortcutExists', res.exists);
          return res.exists;
        },
        fail: (err) => {
          console.error('[快捷入口] 检查失败', err);
          // 检查失败时默认返回false
          tt.setStorageSync('shortcutExists', false);
          return false;
        }
      });
    } catch (error) {
      console.error('[快捷入口] 调用checkShortcut异常', error);
      return false;
    }
  },
  
  // 提示用户添加到快捷入口
  promptAddToShortcut: function() {
    console.log('[快捷入口] 提示添加到快捷入口');
    
    // 检查是否已经提示过用户
    const hasPrompted = tt.getStorageSync('shortcutPrompted');
    if (hasPrompted) {
      console.log('[快捷入口] 今日已提示过添加快捷入口');
      return;
    }
    
    // 尝试调用tt.addToShortcut方法
    try {
      tt.addToShortcut({
        title: '极速闪避',
        imageUrl: '/asset/img/game_logo.png',
        success: (res) => {
          console.log('[快捷入口] 添加成功', res);
          tt.showToast({
            title: '已添加到快捷入口',
            icon: 'success',
            duration: 2000
          });
          // 标记今日已提示
          tt.setStorageSync('shortcutPrompted', true);
        },
        fail: (err) => {
          console.error('[快捷入口] 添加失败', err);
          // 记录失败但不做特殊处理，避免影响游戏体验
        }
      });
    } catch (error) {
      console.error('[快捷入口] 调用addToShortcut异常', error);
    }
  },
  
  // 检查并奖励侧边栏访问
  checkAndRewardSidebarVisit: function() {
    console.log('[侧边栏功能] 检查侧边栏访问奖励');
    
    try {
      // 从侧边栏进入时，标记任务完成并给予奖励
      const today = new Date().toDateString();
      
      if (!this.state.sidebarTask.hasCompletedToday) {
        console.log('[侧边栏功能] 检测到新的侧边栏访问，准备发放奖励');
        
        // 更新任务状态
        this.state.sidebarTask.hasCompletedToday = true;
        this.state.sidebarTask.lastCompleteDate = today;
        
        // 保存到本地存储
        try {
          tt.setStorageSync('sidebarTaskLastCompleteDate', today);
          console.log('[侧边栏功能] 任务状态保存成功');
        } catch (storageError) {
          console.error('[侧边栏功能] 任务状态保存失败', storageError);
        }
        
        // 给予奖励
        this.giveSidebarReward();
      } else {
        console.log('[侧边栏功能] 今日已完成侧边栏任务，跳过奖励');
      }
    } catch (error) {
      console.error('[侧边栏功能] 处理侧边栏奖励异常', error);
    }
  },
  
  // 给予侧边栏奖励
  giveSidebarReward: function() {
    // 计算连续天数奖励
    this.updateContinuousDays();
    
    // 根据连续天数调整奖励
    let rewardScore = 100;
    let rewardMessage = '恭喜获得侧边栏复访奖励！';
    
    // 连续打卡奖励机制
    if (this.state.sidebarTask.continuousDays > 1) {
      // 连续打卡额外奖励
      const extraBonus = Math.min(50 * (this.state.sidebarTask.continuousDays - 1), 200); // 最高额外奖励200分
      rewardScore += extraBonus;
      rewardMessage = `恭喜连续${this.state.sidebarTask.continuousDays}天从侧边栏进入！`;
    }
    
    const reward = {
      score: rewardScore,
      message: rewardMessage
    };
    
    // 更新分数
    this.state.score += reward.score;
    
    // 更新最高分
    if (this.state.score > this.state.highScore) {
      this.state.highScore = this.state.score;
      this.saveHighScore();
    }
    
    // 显示奖励领取弹窗
    this.showRewardPopup(reward);
  },
  
  // 更新连续打卡天数
  updateContinuousDays: function() {
    const today = new Date();
    const lastCompleteDateStr = this.state.sidebarTask.lastCompleteDate;
    
    let newContinuousDays = 1; // 默认今天是第一次打卡
    
    if (lastCompleteDateStr) {
      const lastDate = new Date(lastCompleteDateStr);
      const dayDiff = Math.floor((today - lastDate) / (1000 * 60 * 60 * 24));
      
      // 如果昨天也打卡了，则连续天数+1
      if (dayDiff === 1) {
        newContinuousDays = this.state.sidebarTask.continuousDays + 1;
      }
      // 如果不是昨天打卡，则重置为1
      // 注意：如果是同一天多次打卡，不更新连续天数
    }
    
    // 更新状态并保存
    this.state.sidebarTask.continuousDays = newContinuousDays;
    tt.setStorageSync('sidebarTaskContinuousDays', newContinuousDays);
  },
  
  // 显示奖励领取弹窗
  showRewardPopup: function(reward) {
    tt.showModal({
      title: '奖励领取',
      content: reward.message + '\n获得 ' + reward.score + ' 积分奖励！',
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          console.log('用户确认领取奖励');
        }
      }
    });
  },
  
  // 保存最高分
  saveHighScore: function() {
    try {
      tt.setStorageSync('highScore', this.state.highScore);
      console.log('最高分已保存:', this.state.highScore);
    } catch (e) {
      console.error('保存最高分失败:', e);
    }
  },
  
  // 加载历史最高分
  loadHighScore: function() {
    try {
      const score = tt.getStorageSync('highScore');
      if (score !== null) {
        this.state.highScore = score;
      }
      
      // 加载保存的难度设置
      const savedDifficulty = tt.getStorageSync('gameDifficulty');
      if (savedDifficulty !== null) {
        this.state.difficulty = savedDifficulty;
      }
    } catch (e) {
      console.error('加载数据失败', e);
    }
  },
  
  // 游戏结束处理
  handleGameOver: function() {
    console.log('返回主界面');
    
    // 清除游戏结束状态和弹窗状态
    this.state.gameOver = false;
    this.state.showScorePopup = false;
    
    // 切换回主界面
    this.state.currentScene = 'main';
  },
  
  // 暂停游戏
  pause: function() {
    this.state.isRunning = false;
    this.state.touch.active = false; // 暂停时停止触摸控制
    console.log('游戏暂停');
  },
  
  // 恢复游戏
  resume: function() {
    this.state.isRunning = true;
    console.log('游戏恢复');
  },
  
  // 游戏结束
  gameOver: function() {
    this.state.isRunning = false;
    this.state.touch.active = false;
    console.log('游戏结束，最终分数:', this.state.score);
    
    // 保存最高分
    if (this.state.score > this.state.highScore) {
      this.state.highScore = this.state.score;
      this.saveHighScore();
    }
    
    // 标记为游戏结束状态
    this.state.gameOver = true;
    // 显示分数提示弹窗
    this.state.showScorePopup = true;
  }
};

// 生命周期函数 - 小程序初始化
tt.onShow(function() {
  console.log('小程序启动');
  try {
    // 初始化游戏
    game.init();
    
    // 不需要再次设置登录场景，因为在game.state中已经有默认值
    // 移除这行代码以避免每次显示都重置场景
    
    // 检查是否从侧边栏进入，判断场景值
    try {
      const options = tt.getLaunchOptionsSync();
      const scene = options.scene;
      
      console.log('进入场景值:', scene);
      
      // 根据文档，抖音侧边栏场景值为 021036 或 021012
      // 抖音极速版侧边栏场景值为 101036
      if (scene === '021036' || scene === '021012' || scene === '101036') {
        console.log('从侧边栏进入游戏');
        // 检查是否需要发放奖励
        game.checkAndRewardSidebarVisit();
      }
    } catch (sceneError) {
      console.error('[侧边栏功能] 场景值检查异常:', sceneError);
      // 不影响游戏正常运行，继续执行
    }
    
    // 检查快捷入口状态并提示用户添加
    setTimeout(() => {
      game.checkShortcutStatus();
      // 随机决定是否提示用户添加到快捷入口（增加概率控制，避免频繁提示）
      if (Math.random() < 0.3) {
        game.promptAddToShortcut();
      }
    }, 3000); // 延迟3秒执行，避免在游戏启动时立即弹出提示
  } catch (initError) {
    console.error('游戏初始化异常:', initError);
  }
});

// 生命周期函数 - 小程序隐藏
tt.onHide(function() {
  console.log('小程序隐藏');
  // 暂停游戏
  game.pause();
});

// 注意：抖音小游戏环境中不支持tt.onUnload生命周期函数
// 这里不使用onUnload回调，资源清理可以在其他适当的地方进行

